//
//  DocumentViewController.m
//  Alfresco
//
//  Created by Michael Muller on 9/3/09.
//  Copyright 2010 Zia Consulting.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

#import "DocumentViewController.h"
#import "SavedDocument.h"

#define kWebViewTag 1234

@implementation DocumentViewController

@synthesize fileData;
@synthesize fileName;
@synthesize isFavorite;
@synthesize favoriteButton;

- (void)dealloc {
	[fileData release];
	[fileName release];
	[favoriteButton release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	// write the file contents to the file system
	NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:self.fileName];
	[self.fileData writeToFile:path atomically:NO];
	
	// get a URL that points to the file on the filesystem
	NSURL *url = [NSURL fileURLWithPath:path];
	NSURLRequest *request = [NSURLRequest requestWithURL:url];

	// get a pointer to the web view
	UIWebView *webView = (UIWebView *) [self.view viewWithTag:kWebViewTag];
	NSAssert(webView, @"could not find web view");

	// load the document into the view
	webView.scalesPageToFit = YES;
	[webView loadRequest:request];
	
	// if this file has been saved as a favorite, indicate so by displaying
	// a filled-in star on the "favorites" button (rather than the empty 
	// one which is displayed by default)

	if ([SavedDocument isSaved:fileName]) {
		UIImage *img = [UIImage imageNamed:@"starFilled.png"];
		favoriteButton.image = img;
		[img release];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (IBAction)sendMail {
	MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
	
	[mailer addAttachmentData:[NSData dataWithContentsOfFile:[SavedDocument pathToTempFile:fileName]] mimeType:[SavedDocument mimeTypeForFilename:fileName] fileName:fileName];	
	[mailer setSubject:fileName];
	[mailer setMessageBody:@"Sent from my document repository using Fresh Docs, the native iPhone client for Alfresco." isHTML:NO];
	
	[self presentModalViewController:mailer animated:YES];
	mailer.mailComposeDelegate = self;
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)addToFavorites {
	if ([SavedDocument isSaved:fileName]) {
		[SavedDocument unsave:fileName];
		UIImage *img = [UIImage imageNamed:@"starEmpty.png"];
		favoriteButton.image = img;
		[img release];
	}
	else {
		[SavedDocument save:fileName];
		UIImage *img = [UIImage imageNamed:@"starFilled.png"];
		favoriteButton.image = img;
		[img release];
	}
}

@end
